/* eslint-disable vue/return-in-computed-property */
/* eslint-disable no-new-object */
<template>
  <div>
    <el-form ref="ruleForms" :model="ruleForms" :rules="rules">
      <el-table
        ref="table"
        :data="ruleForms.temp"
        style="width: 100%"
        :highlight-current-row="true"
        max-height="500"
      >
        <el-table-column
          :key="Math.random()"
          prop="date"
          label="文件名称"
          min-width="200"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-form-item
              :prop="'temp.' + scope.$index + '.documentName'"
              :rules="rules.documentName"
            >
              <el-input
                v-model.trim="scope.row.documentName"
                :disabled="flowStatus > 1"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          :key="Math.random()"
          width="160"
          prop="content"
          label="文件等级"
        >
          <template slot-scope="scope">
            <!-- :prop="'temp.' + scope.$index + '.documentLevel '" -->
            <el-form-item :rules="rules.documentLevel">
              <el-select
                v-model="scope.row.documentLevel"
                :disabled="flowStatus > 1"
                @change="handleLevelChange($event, scope.$index, 1)"
              >
                <el-option
                  v-for="item in levels"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          :key="Math.random()"
          width="160"
          prop="content"
          label="文件属性"
        >
          <template slot-scope="scope">
            <el-form-item
              :prop="'temp.' + scope.$index + '.documentProperty'"
              :rules="rules.documentProperty"
            >
              <el-select
                v-model="scope.row.documentProperty"
                :disabled="flowStatus > 1"
                @change="handlePropertyChange($event, scope.$index)"
              >
                <el-option
                  v-for="item in categories[scope.$index]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          :key="Math.random()"
          prop="date"
          label="文件编号"
          min-width="220"
        >
          <template slot-scope="scope">
            <el-form-item
              :prop="'temp.' + scope.$index + '.documentCode'"
              :rules="rules.documentCode"
            >
              <el-input
                v-model.trim="scope.row.documentCode"
                :disabled="flowStatus > 1"
                @change="inputChange($event, scope.$index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          v-if="flowStatus > 1"
          :key="Math.random()"
          prop="content"
          label="版本号"
          width="150"
        >
          <template slot-scope="scope">
            <el-form-item class="form-select">
              <el-input
                v-model="scope.row.documentVersion"
                disabled
                :min="0"
                :max="9"
                controls-position="right"
                style="width: 80px"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          v-if="flowStatus == 1"
          :key="Math.random()"
          prop="content"
          label="版本号"
          width="150"
        >
          <template slot-scope="scope">
            <el-form-item class="form-select">
              <el-input
                v-model="scope.row.documentVersion"
                :min="0"
                :max="9"
                controls-position="right"
                style="width: 80px"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          :key="Math.random()"
          prop="date"
          label="来源信息"
          width="150"
        >
          <template slot-scope="scope">
            <el-form-item>
              <el-input
                v-model.trim="scope.row.sourceInfo"
                :disabled="flowStatus > 1"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          v-if="flowStatus == 3"
          :key="Math.random()"
          width="250"
          prop="date"
          label="文件模板"
        >
          <template slot-scope="scope">
            <el-form-item :prop="'temp.' + scope.$index + '.modeDocumentName'">
              <el-input v-model="scope.row.modeDocumentName" :disabled="true" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          :key="Math.random()"
          fixed="right"
          label="操作"
          width="200px"
        >
          <template slot-scope="scope">
            <el-form-item>
              <!-- 选择 -->
              <el-tooltip effect="dark" content="选择文件模板" placement="top">
                <el-button
                  v-if="flowStatus == 1"
                  size="mini"
                  circle
                  @click.native="openDialog(1, scope.row, scope.$index)"
                  ><i class="el-icon-search" />
                </el-button>
              </el-tooltip>

              <!-- 上传 -->
              <el-tooltip effect="dark" content="上传文件" placement="top">
                <el-button
                  v-if="flowStatus > 0 && flowStatus !== 5 && flowStatus < 7"
                  size="mini"
                  circle
                  @click.native="openDialog(0, scope.row, scope.$index)"
                  ><i class="el-icon-upload2" />
                </el-button>
              </el-tooltip>
              <!-- 编辑 -->
              <el-tooltip effect="dark" content="编辑文件" placement="top">
                <el-button
                  v-if="(flowStatus) => 1 && flowStatus < 9"
                  size="mini"
                  circle
                  @click.native="openDocument('edit', scope.row)"
                  ><i class="el-icon-edit" />
                </el-button>
              </el-tooltip>

              <!-- 查看 -->
              <el-tooltip effect="dark" content="查看文件" placement="top">
                <el-button
                  v-if="flowStatus >= 2"
                  size="mini"
                  circle
                  @click.native="openDocument('view', scope.row)"
                  ><i class="el-icon-view" />
                </el-button>
              </el-tooltip>
              <!-- 下载 -->
              <el-tooltip effect="dark" content="下载文件" placement="top">
                <el-button
                  v-if="flowStatus > 3 && flowStatus !== 5 && flowStatus < 7"
                  size="mini"
                  circle
                  @click.native="fileDownload(scope.row)"
                  ><i class="el-icon-download" />
                </el-button>
              </el-tooltip>

              <!-- 删除 -->
              <el-tooltip effect="dark" content="删除" placement="top">
                <el-button
                  v-if="flowStatus == 1"
                  size="mini"
                  circle
                  @click.native="Delete_information(scope.$index, scope.row)"
                  ><i class="el-icon-remove-outline" />
                </el-button>
              </el-tooltip>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="my-but-box">
      <el-button v-if="flowStatus == 1" class="my-but" @click="addTable"
        ><i class="el-icon-circle-plus-outline" />
      </el-button>
    </div>
    <UploadingFile
      :uploading-file-data="UploadingFileData"
      @uploadingdata="uploadingdata"
    />
    <SelectFile
      :select-file-data="SelectFileData"
      @templateData="templateData"
    />
  </div>
</template>

<script>
import { listDictTreeItem } from '@/api/base/dict'
import UploadingFile from '@/views/flow/components/UploadingFile'
import SelectFile from '@/views/flow/components/SelectFile'
import { listUserGroupAll } from '@/api/uc/userGroup'
import { copy, generateCode } from '@/api/fd/document'
import { fileDownload } from '@/utils/redo_download.js'
import { getDocumentCodeIsExisted } from '@/api/fd/document.js'

export default {
  components: { UploadingFile, SelectFile },
  props: ['TabelBoxData'],
  data() {
    return {
      tempForms: {},
      rules: {
        documentLevel: [
          { required: true, message: '必填字段', trigger: 'change' }
        ],
        documentProperty: [
          { required: true, message: '必填字段', trigger: 'change' }
        ],
        documentName: [
          { required: true, message: '必填字段', trigger: 'blur' }
        ],
        documentCode: [
          { required: true, message: '必填字段', trigger: 'blur' }
        ],
        documentVersion: [
          { required: true, message: '必填字段', trigger: 'blur' }
        ],
        reason: [{ required: true, message: '必填字段', trigger: 'blur' }],
        modeDocumentName: [
          { required: true, message: '请上传文件', trigger: 'blur' }
        ]
      },
      ruleForms: {
        temp: [
          {
            documentName: null,
            documentCode: null,
            documentLevel: null,
            documentProperty: null,
            documentVersion: 'A0',
            sourceInfo: null,
            modeDocumentName: null,
            documentId: null
          }
        ]
      },

      DocumentVersionData: '',
      flowStatus: '',
      levels: [],
      categories: [],
      roles: null,
      userGroup: [],
      UploadingFileData: {},
      SelectFileData: {},
      v3: null,
      v4: null,
      result: '0',
      visible: false
    }
  },
  computed: {},
  watch: {
    TabelBoxData(data) {
      this.flowStatus = data.flowStatus
      this.roles = data.roles
      if (data.temp.length > 0) {
        const newData = Array.from(data.temp)
        newData.forEach((e, index) => {
          e.documentLevel = e.documentLevel + ''
          this.handleLevelChange(e.documentLevel, index, 2)
          e.modeDocumentName = ''
        })
        this.ruleForms.temp = newData || []
      }
      this.loadLevelOptions()
    },
    'ruleForms.temp'(data) {}
  },
  methods: {
    fileDownload,
    inputChange(val, index) {
      if (this.ruleForms.temp[index].documentLevel) {
        this.ruleForms.temp.forEach((e, index2) => {
          if (e.documentCode === val && index !== index2) {
            this.$message.warning('表单文件编号重复')
            this.ruleForms.temp[index].documentCode = ''
          } else {
            getDocumentCodeIsExisted({ code: val }).then((res) => {
              if (!res.data) {
                this.$message.warning('文件编号已使用')
                this.ruleForms.temp[index].documentCode = ''
              } else {
                return
              }
            })
          }
        })
      } else {
        this.$message.warning('请选择文件属性')
        this.ruleForms.temp[index].documentCode = ''
      }
      // this.ruleForms.temp[index].documentCode=''
    },
    // 添加
    addTable() {
      this.ruleForms.temp.push({
        documentName: null,
        documentLevel: null,
        documentProperty: null,
        documentVersion: 'A0',
        documentCode: null,
        sourceInfo: null,
        modeDocumentName: null,
        documentId: null
      })
    },
    inputData(val, index) {
      if (val) {
        this.ruleForms.temp[index].documentVersion = val || 'A0'
      }
    },
    Delete_information(index) {
      this.$confirm('此操作将删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.ruleForms.temp.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleLevelChange(val, index, type) {
      for (let i = 0, len = this.levels.length; i < len; i++) {
        if (this.levels[i].value === val) {
          this.categories[index] = this.levels[i].children
          if (type !== 2) {
            if (this.ruleForms.temp[index].documentProperty) {
              this.ruleForms.temp[index].documentProperty = ''
            }
          }
        }
      }
    },
    handlePropertyChange(val, index) {
      const type = this.ruleForms.temp[index].documentLevel === 1 ? '1' : '0'
      generateCode({
        code: val,
        showLength: 3,
        type: Number(type)
      }).then((res) => {
        this.ruleForms.temp[index].documentCode = res.data.code
        this.$refs.ruleForms.clearValidate('temp.' + index + '.documentCode')
        // this.inputChange(res.data.code, index)
      })
    },
    loadLevelOptions() {
      listDictTreeItem({ dictGroupCode: 'document_category' }).then((res) => {
        const array = res.data
        if (array) {
          if (this.roles.indexOf('qa') === -1) {
            for (let i = 0, len = array.length; i < len; i++) {
              if (array[i].value === '1') {
                array.splice(i, 1)
                break
              }
            }
          }
        }
        this.levels = array
      })
    },
    async backTempData() {
      let valid = true
      if (this.result !== 3) {
        valid = await this.$refs.ruleForms.validate().catch((err) => {
          return err
        })
      }
      const data = { valid: valid, documentFlowInfoList: this.ruleForms.temp }
      return data
    },
    openDialog(val, row, index) {
      if (row.documentCode === null) {
        this.$message.warning('请先设置文件等级、文件属性、文件编号')
      } else {
        if (val === 0) {
          let isType = 1
          if (this.flowStatus === 1) {
            isType = 2
          }
          this.openDialogType = '1'
          this.UploadingFileData = {
            deleteDialog: true,
            value: '',
            documentItem: isType === 2 ? row.documentCode : row.documentId,
            documentId: row.documentId,
            index: index,
            type: isType,
            level: row.documentLevel
          }
          return
        } else {
          this.openDialogType = '2'
          this.SelectFileData = {
            deleteDialog: true,
            row: row,
            index: index
          }
        }
        this.getUserGroup()
      }
    },
    getUserGroup() {
      // 获取部门
      listUserGroupAll({ type: 0 }).then((res) => {
        res.data.forEach((item) => {
          if (item.type == 1) {
            var data = {
              value: item.userGroupId,
              label: item.userGroupName
            }
            this.userGroup.push(data)
          }
          if (item.type == 2) {
            var data = {
              value: item.userGroupId,
              label: item.userGroupName
            }
            this.userGroup.push(data)
          }
        })
      })
    },
    // 文件上传
    uploadingdata(data) {
      const { row, update } = data
      const newTemp = Array.from(this.ruleForms.temp)
      newTemp[row.index].modeDocumentName = update[0].documentName
      newTemp[row.index].documentId = update[0].documentId
      this.ruleForms.temp = newTemp
    },
    // 获取选择模板组件数据
    async templateData(data) {
      const { SelectFileData, document } = data
      // 目标库id
      const destRepositoryId = 3
      const copyData = {
        destRepositoryId: destRepositoryId,
        documentId: document.value,
        documentCode: SelectFileData.row.documentCode,
        level: SelectFileData.row.documentLevel
      }
      const newTemp = Array.from(this.ruleForms.temp)
      await copy(copyData).then((res) => {
        newTemp[SelectFileData.index].modeDocumentName = res.data.documentName
        newTemp[SelectFileData.index].documentId = res.data.documentId
      })

      this.ruleForms.temp = newTemp
    },
    openDocument(val, row) {
      if (row.fileExtension.indexOf('.pdf') !== -1) {
        window.open(
          process.env.VUE_APP_BASE_API +
            '/api/fd/pdf/get_document_by_pdf?documentId=' +
            row.documentId
        )
      } else {
        window.open(
          'onlyoffice/createDocument.html?&token=' +
            this.$store.getters.token +
            '&documentId=' +
            row.documentId +
            '&mode=' +
            val +
            '&urldata=' +
            process.env.VUE_APP_BASE_API
        )
      }
    },
    backResult(val) {
      this.result = val
    }
  }
}
</script>

<style   scoped>
.my-but {
  font-size: 20px;
}
.form-select {
  display: flex;
}

.form-select >>> .el-form-item__content {
  display: flex;
}
</style>
